package com.zyl.basewidget;

import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.widget.RemoteViews;

public class BaseWidget extends AppWidgetProvider {

	
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
	  {
	    int i = appWidgetIds.length;
	    for (int j = 0;j < i ; j++)
	    {
	      new Timer().scheduleAtFixedRate(new ATime(context, appWidgetManager, appWidgetIds[j]), 1L, 3600000L);
	    }
	    
	    super.onUpdate(context, appWidgetManager, appWidgetIds);
	  }

	  public class ATime extends TimerTask
	  {
	    int appWidgetId;
	    AppWidgetManager appWidgetManager;
	    Context context;

	    public ATime(Context paramContext, AppWidgetManager paramAppWidgetManager, int appWidgetId)
	    {
	      this.context = paramContext;
	      this.appWidgetManager = paramAppWidgetManager;
	      this.appWidgetId = appWidgetId;
	    }

	    public void run()
	    {
	    	BaseWidget.updateAppWidget(this.context, this.appWidgetManager, this.appWidgetId);
	    }
	  }

	  
	public static void updateAppWidget(Context context,AppWidgetManager appWidgetManager, int appWidgetId)
	{
			RemoteViews remoteViews  = new RemoteViews(context.getPackageName(), R.layout.widget);
			
			String[] config =BaseConf.loadPref(context,appWidgetId);
			
			
			
			String[] arrayOfString2 = config[1].split("-");
		    long l = getCountDays(Integer.parseInt(arrayOfString2[0]), Integer.parseInt(arrayOfString2[1]), Integer.parseInt(arrayOfString2[2]));

			
			remoteViews.setTextViewText(R.id.Days,  l+"");
			remoteViews.setTextViewText(R.id.Title, config[0]);
			remoteViews.setTextViewText(R.id.Date,  config[1]);
			appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
		 
	}
	
	public static long getCountDays(int year, int month, int day)
	  { 
	    TimeZone timeZone = TimeZone.getTimeZone("GMT+08:00");
	    GregorianCalendar calendar1 = new GregorianCalendar(timeZone);
	    GregorianCalendar calendar2 = new GregorianCalendar(timeZone);
	    calendar2.set(year, month - 1, day);
	    return ((calendar2.getTimeInMillis() - calendar1.getTimeInMillis()) / 1000L / 86400L);
	  }
}